from sys import argv
import os

"""
模拟文件路径相关：
"""

class Path:
    """
    维护一个文件指向
    记录当前位置和操作位置
    """

    def __init__(self, operate: int = 0):
        self.now = None    # 当前唯一可变的维护路径
        self.op = self.formatting(os.path.abspath(__file__))  # 本文件位置
        self.fp = self.formatting(argv[0])  # 调用此类的文件的位置
        self.set(operate)  # 文件位置记录

    def print(self):
        print('当前路径:', self.now)
        print('脚本路径:', self.op)
        print('调用路径:', self.fp)

    def formatting(self, path: str) -> str:
        """将path格式调整"""
        return path.replace('\\', '/')

    def set(self, operate: int = 0):
        """:param operate: 0-path文件路径 else-当前文件路径"""
        self.now = self.op if operate == 0 else self.fp

    def check(self, path: str) -> str:
        if path[-1] == '/':
            path = path[:-1]
        return path

    def back(self, step: int = 1):
        """对路径回退"""
        path = self.check(self.now)
        if step == 0:
            cut = path.find(':/') + 2
            path = path[:cut]
        else:
            for i in range(step):
                cut = path.rfind('/')
                path = path[:cut]
        self.now = self.formatting(path)

    def to(self, where: str, goto: bool = True):
        """对路径步进，不存在将自生成文件夹"""
        path = self.check(self.now)
        if path[-1] != '/':
            path += '/'
        path += where
        if not os.path.exists(path):
            os.mkdir(path)
            print('>新建文件夹：' + where)
        path += '/'

        if goto:
            self.now = self.formatting(path)
        return path


    def new_file(self, filename, data=''):
        """新建文件"""
        with open(self.now + filename, 'w+', encoding='utf-8') as ff:
            ff.write(data)
